package net.melon.review.inst.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import net.esj.basic.dao.querybuilder.QueryBuilder;
import net.esj.basic.service.impl.DefaultServiceImpl;
import net.esj.basic.utils.Validators;
import net.melon.review.inst.service.ReviewService;
import net.melon.review.pojo.Area;
import net.melon.review.pojo.Review;
import net.melon.sso.pojo.Member;

@Service
public class ReviewServiceImpl extends DefaultServiceImpl implements ReviewService {
	
	private static List<Area> areaList = new ArrayList<Area>();
	
	private static Map<Integer, List<Area>> areaListMap = new HashMap<Integer, List<Area>>();
	
	public static Map<Integer, Area> areaMap = new HashMap<Integer, Area>();
	

	public void setAreaList(){
		if(Validators.isEmpty(areaList)){
			areaList = getAreas();
			for(Area area : areaList){
				List<Area> areas = areaListMap.get(area.getParent_id());
				if(areas==null){
					areas = new ArrayList<Area>();
				}
				areas.add(area);
				areaListMap.put(area.getParent_id(), areas);
				areaMap.put(area.getId(),area);
			}
		}
	}
	
	@Override
	public List<Area> getAreaByParentId(Integer parentId){
		setAreaList();
		List<Area> list = areaListMap.get(parentId);
		return list;
	}
	
	@Override
	public Area getAreaMapByKey(int province) {
		setAreaList();
		return areaMap.get(province);
	}

	private List<Area> getAreas() {
		QueryBuilder<Area> qb = createQueryBuilder(Area.class);
		return queryListByQueryBuilder(qb);
	}

	@Override
	public Review getReviewByMember(Member member) {
		QueryBuilder<Review> qb = createQueryBuilder(Review.class);
		qb.eq("memberId", member.getId());
		return (Review) queryFirst(qb);
	}

	@Override
	public void changeState(Integer reviewId,int state) {
		Review review = get(reviewId, Review.class);
		if(review!=null){
			review.setState(state);
		}
	}
	
}
